<template>
  <view class="dict-container">
    <!-- 搜索区域 -->
    <view class="search-box">
      <view class="search-form">
        <view class="search-item">
          <text class="label">字典名称：</text>
          <input
            v-model="queryParams.dictName"
            type="text"
            placeholder="请输入字典名称"
            @confirm="handleQuery"
          />
        </view>
        <view class="search-item">
          <text class="label">字典类型：</text>
          <input
            v-model="queryParams.dictType"
            type="text"
            placeholder="请输入字典类型"
            @confirm="handleQuery"
          />
        </view>
        <view class="search-item">
          <text class="label">状态：</text>
          <picker @change="handleStatusChange" :value="statusIndex" :range="statusOptions" range-key="label">
            <view class="picker-box">
              <text :class="{ 'placeholder': !queryParams.status }">
                {{ statusOptions[statusIndex].label }}
              </text>
              <uni-icons type="bottom" size="12" color="#909399"></uni-icons>
            </view>
          </picker>
        </view>
      </view>
      <view class="btn-group">
        <button class="btn search-btn" @tap="handleQuery">
          <uni-icons type="search" size="14" color="#fff"></uni-icons>
          <text>搜索</text>
        </button>
        <button class="btn reset-btn" @tap="resetQuery">
          <uni-icons type="refresh" size="14" color="#606266"></uni-icons>
          <text>重置</text>
        </button>
        <button class="btn add-btn" @tap="handleAdd">
          <uni-icons type="plusempty" size="14" color="#fff"></uni-icons>
          <text>新增</text>
        </button>
      </view>
    </view>

    <!-- 字典列表 -->
    <view class="dict-list" v-if="dictList.length > 0">
      <view v-for="(item, index) in dictList" :key="index" class="dict-item" @tap="handleData(item)">
        <view class="dict-info">
          <view class="info-row">
            <text class="label">字典名称：</text>
            <text class="value">{{ item.dictName }}</text>
          </view>
          <view class="info-row">
            <text class="label">字典类型：</text>
            <text class="value">{{ item.dictType }}</text>
          </view>
          <view class="info-row">
            <text class="label">状态：</text>
            <text class="value" :class="item.status === '0' ? 'text-success' : 'text-danger'">
              {{ item.status === '0' ? '正常' : '停用' }}
            </text>
          </view>
          <view class="info-row" v-if="item.remark">
            <text class="label">备注：</text>
            <text class="value">{{ item.remark }}</text>
          </view>
        </view>
        <view class="dict-actions">
          <button class="action-btn edit-btn" @tap.stop="handleEdit(item)">
            <uni-icons type="compose" size="14" color="#409eff"></uni-icons>
          </button>
          <button class="action-btn delete-btn" @tap.stop="handleDelete(item)" v-if="!item.system">
            <uni-icons type="trash" size="14" color="#f56c6c"></uni-icons>
          </button>
        </view>
      </view>

      <!-- 加载更多提示 -->
      <uni-load-more :status="loadMoreStatus" :icon-size="16" :content-text="contentText" />
    </view>

    <!-- 空数据提示 -->
    <view v-else class="empty-box">
      <uni-icons type="info" size="50" color="#999"></uni-icons>
      <text class="empty-text">暂无字典数据</text>
    </view>
  </view>
</template>

<script>
import { listType, delType } from '@/api/system/dict/type'

export default {
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      dictList: [],
      loading: false,
      hasMore: true,
      total: 0,
      loadMoreStatus: 'more',
      contentText: {
        contentdown: '上拉显示更多',
        contentrefresh: '正在加载...',
        contentnomore: '没有更多数据了'
      },
      statusOptions: [
        { label: '全部', value: '' },
        { label: '正常', value: '0' },
        { label: '停用', value: '1' }
      ],
      statusIndex: 0
    }
  },
  onLoad() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    async getList(type = 'more') {
      if (this.loading) return
      this.loading = true

      try {
        // 构造查询参数，过滤掉空值
        const params = Object.keys(this.queryParams).reduce((acc, key) => {
          if (this.queryParams[key] !== undefined && this.queryParams[key] !== '') {
            acc[key] = this.queryParams[key]
          }
          return acc
        }, {})

        const res = await listType(params)

        if (res.code === 200) {
          const { rows, total } = res

          if (type === 'refresh' || params.pageNum === 1) {
            this.dictList = rows
          } else {
            this.dictList = [...this.dictList, ...rows]
          }

          this.total = total
          this.hasMore = this.dictList.length < total
          this.loadMoreStatus = this.hasMore ? 'more' : 'noMore'
        }
      } catch (error) {
        this.loadMoreStatus = 'more'
        uni.showToast({
          title: '获取字典列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        if (type === 'refresh') {
          uni.stopPullDownRefresh()
        }
      }
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.dictList = []
      this.hasMore = true
      this.loadMoreStatus = 'more'
      this.getList('refresh')
    },

    // 重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      }
      this.statusIndex = 0
      this.handleQuery()
    },

    // 状态选择改变
    handleStatusChange(e) {
      this.statusIndex = e.detail.value
      this.queryParams.status = this.statusOptions[this.statusIndex].value
    },

    // 下拉刷新
    onPullDownRefresh() {
      this.queryParams.pageNum = 1
      this.dictList = []
      this.hasMore = true
      this.getList('refresh')
    },

    // 上拉加载更多
    onReachBottom() {
      if (this.hasMore && !this.loading) {
        this.queryParams.pageNum++
        this.getList('more')
      }
    },

    // 新增字典
    handleAdd() {
      uni.navigateTo({
        url: '/pages/system/dict/form'
      })
    },

    // 编辑字典
    handleEdit(item) {
      uni.navigateTo({
        url: `/pages/system/dict/form?dictId=${item.dictId.toString()}`
      })
    },

    // 查看字典数据
    handleData(item) {
      uni.navigateTo({
        url: `/pages/system/dict/data?dictId=${item.dictId}&dictType=${item.dictType}&dictName=${item.dictName}`
      })
    },

    // 删除字典
    handleDelete(item) {
      uni.showModal({
        title: '提示',
        content: `是否确认删除字典名称为"${item.dictName}"的数据项？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await delType(item.dictId)
              if (result.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.handleQuery()
              }
            } catch (error) {
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.dict-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;

  .search-box {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

    .search-form {
      .search-item {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          width: 140rpx;
          font-size: 28rpx;
          color: #606266;
          font-weight: 500;
        }

        input {
          flex: 1;
          height: 72rpx;
          background-color: #f8f9fa;
          border-radius: 8rpx;
          padding: 0 24rpx;
          font-size: 28rpx;
          color: #2c3e50;

          &::placeholder {
            color: #909399;
          }
        }

        .picker-box {
          flex: 1;
          height: 72rpx;
          background-color: #f8f9fa;
          border-radius: 8rpx;
          padding: 0 24rpx;
          font-size: 28rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;

          text {
            color: #2c3e50;

            &.placeholder {
              color: #909399;
            }
          }

          .uni-icons {
            margin-left: 12rpx;
          }
        }
      }
    }

    .btn-group {
      display: flex;
      gap: 20rpx;
      margin-top: 30rpx;
      padding-top: 30rpx;
      border-top: 2rpx solid #f0f0f0;

      .btn {
        flex: 1;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12rpx;
        font-size: 28rpx;
        border-radius: 8rpx;
        transition: all 0.3s;

        &:active {
          transform: scale(0.98);
          opacity: 0.9;
        }

        &.search-btn {
          background-color: #409eff;
          color: #fff;

          &:active {
            background-color: #3a8ee6;
          }
        }

        &.reset-btn {
          background-color: #f5f7fa;
          color: #606266;
          border: 2rpx solid #dcdfe6;

          &:active {
            background-color: #e9e9eb;
          }
        }

        &.add-btn {
          background-color: #67c23a;
          color: #fff;

          &:active {
            background-color: #5daf34;
          }
        }
      }
    }
  }

  .dict-list {
    .dict-item {
      position: relative;
      background-color: #fff;
      padding: 32rpx;
      margin-bottom: 24rpx;
      border-radius: 16rpx;
      box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

      .dict-info {
        padding-right: 100rpx; // 为操作按钮预留空间

        .info-row {
          display: flex;
          margin-bottom: 16rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .label {
            width: 140rpx;
            font-size: 28rpx;
            color: #606266;
          }

          .value {
            flex: 1;
            font-size: 28rpx;
            color: #2c3e50;
            font-weight: 500;

            &.text-success {
              color: #67c23a;
            }

            &.text-danger {
              color: #f56c6c;
            }
          }
        }
      }

      .dict-actions {
        position: absolute;
        right: 32rpx;
        top: 32rpx;
        display: flex;
        gap: 16rpx;

        .action-btn {
          width: 56rpx;
          height: 56rpx;
          padding: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 28rpx;
          background-color: #f8f9fa;
          border: none;

          &:active {
            opacity: 0.8;
          }

          &.edit-btn {
            &:active {
              background-color: #ecf5ff;
            }
          }

          &.delete-btn {
            &:active {
              background-color: #fef0f0;
            }
          }
        }
      }

      &:active {
        opacity: 0.9;
      }
    }
  }

  .empty-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx 0;
    background-color: #fff;
    border-radius: 16rpx;
    margin-top: 24rpx;

    .empty-text {
      margin-top: 24rpx;
      font-size: 28rpx;
      color: #909399;
      letter-spacing: 1rpx;
    }
  }
}
</style>